﻿module app.handler.payment.base;
import std.json;
import app.helper.appinfo;
import std.datetime;
import std.experimental.logger;
import std.conv;
import std.typetuple;
import std.typecons;
import std.algorithm.sorting;
import app.service.paybillservice;
import app.model;
import core.stdc.time;
import std.string;
public import app.utils;

abstract class PayHandlerBase
{
	protected JSONValue orderJson;
	private string _channel;
	
	@property string channel(){return _channel;}
	@property void channel(string _c){_channel = _c;}
	
	void setOrderJson(JSONValue json)
	{
		orderJson = json;
	}
	
	JSONValue pay(){
		string bill_id = "";
		string[string] res = createBillAndSign(bill_id);
		JSONValue js;
		js["bill_id"] = bill_id;//数据生成的平台id
		js["channel"] = orderJson["channel"].str;
		js["credential"] = JSONValue(res);
		return js;
	}
	
	string[string] createBillAndSign(out string bill_id);
	
	///创建订单返回单号
	string saveBill()
	{
		PayBill bill = new PayBill();
		bill.outTradeNo = orderJson["order_no"].str;
		bill.appid = orderJson["appid"].str;
		bill.amount = cast(int)(orderJson["amount"].integer);
		bill.createTime = time(null);
		bill.channel = orderJson["channel"].str;
		bill.status = 0;
		bill.body_ = orderJson["body"].str;
		bill.subject = orderJson["subject"].str;
		bill.notifyUrl = orderJson["notify_url"].str;
		if("passback_params" in orderJson && orderJson["passback_params"].type ==  JSON_TYPE.STRING)
		{
			bill.passbackParams = orderJson["passback_params"].str;
		}
		
		return PayBillService.getInstance.insertData(bill);
	}
	///获取应用在此支付渠道下的所有配置信息
	string[string] getAppChannelConfig(){
		import app.helper.appinfo;
		return getAppChannelConf(toLower(orderJson["appid"].str),toLower(orderJson["channel"].str));
	}
	
	void checkOutTradeNoIsPay()
	{
		import std.format;
		import app.model.db;
		auto num = PayBillService.getInstance.getDataNumByWhere(format("appid=%s and out_trade_no=%s and status!=0", 
				DB().escapeLiteral(orderJson["appid"].str),
				DB().escapeLiteral(orderJson["order_no"].str)
				));
		if(num != 0)
			throwExceptionBuild!"OrderAlreadyPayed"("Order Already Payed ");
	}
	
	
	
}

